import pyqtgraph as pg
from PyQt5.QtWidgets import QWidget, QVBoxLayout
import numpy as np

class DynamicPlot(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        layout = QVBoxLayout(self)
        self.plot_widget = pg.PlotWidget()
        layout.addWidget(self.plot_widget)
        self.plot_widget.setBackground('w')
        self.curve = self.plot_widget.plot(pen='b')
        self.data = []

    def update_plot(self, value):
        self.data.append(value)
        if len(self.data) > 100:  # 保持最近100个数据点
            self.data.pop(0)
        self.curve.setData(self.data)

class NetworkVisualization(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        layout = QVBoxLayout(self)
        self.plot_widget = pg.PlotWidget()
        layout.addWidget(self.plot_widget)
        self.plot_widget.setBackground('w')
        
    def plot_network(self, nodes, edges):
        self.plot_widget.clear()
        # 绘制节点
        scatter = pg.ScatterPlotItem(size=10, brush=pg.mkBrush(color='b'))
        scatter.addPoints(pos=nodes)
        self.plot_widget.addItem(scatter)
        
        # 绘制边
        for edge in edges:
            line = pg.PlotCurveItem(x=[edge[0][0], edge[1][0]], 
                                  y=[edge[0][1], edge[1][1]], 
                                  pen=pg.mkPen('r', width=1))
            self.plot_widget.addItem(line)

class FeatureVisualization(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        layout = QVBoxLayout(self)
        self.plot_widget = pg.PlotWidget()
        layout.addWidget(self.plot_widget)
        self.plot_widget.setBackground('w')
        
    def plot_features(self, features, labels=None):
        self.plot_widget.clear()
        colors = ['b', 'r', 'g', 'c', 'm', 'y']
        
        if labels is None:
            scatter = pg.ScatterPlotItem(size=10, brush=pg.mkBrush(color='b'))
            scatter.addPoints(pos=features)
            self.plot_widget.addItem(scatter)
        else:
            unique_labels = np.unique(labels)
            for i, label in enumerate(unique_labels):
                mask = labels == label
                scatter = pg.ScatterPlotItem(size=10, 
                                          brush=pg.mkBrush(color=colors[i % len(colors)]))
                scatter.addPoints(pos=features[mask])
                self.plot_widget.addItem(scatter) 